using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using MessageGateway;

namespace Translator
{

    public class MessageTranslatorComponent : SimpleFilter
    {
        protected XslCompiledTransform xslt;

        public MessageTranslatorComponent(IMessageReceiver input, IMessageSender output, IXPathNavigable xsltDoc)
            : base (input, output)
        {
            xslt = new XslCompiledTransform();
            xslt.Load(xsltDoc);
        }

        public MessageTranslatorComponent(string inputQueue, string outputQueue, IXPathNavigable xsltDoc, 
                                          IMessageGatewayFactory factory) :
            this(factory.GetReceiverInstance(inputQueue), factory.GetSenderInstance(outputQueue), xsltDoc)
        {
        }

        protected override void OnMessage(XmlDocument message)
        {
            XmlDocument result = new XmlDocument();
                using (XmlWriter writer = result.CreateNavigator().AppendChild()) {
                xslt.Transform(message, writer);
            }
            output.Send(result);
        }
    }
}
